/* Copyright (C) 2014-2015 Mammoth Inc. */

var m = new M("profile");

var more = [true, true];
var stop = [true, true];
var page = [1, 1];
var divArray = ["#question", "#answer"];
var valNameArray = ["questionlist", "answerlist"];
var str = ["暂无问题", "暂无回答"];
var uid = window.location.href.substring(31);
if(uid.indexOf("#") != -1) {
    uid = uid.substr(0,uid.indexOf("#"));
}
var circleWidth;

$(function() {
    $("#mm_prof_oj").hide();
    $("#mm_prof_oj").next().hide();
    var format = function(time, format){ 
        var t = new Date(time); 
        var tf = function(i){return (i < 10 ? '0' : '') + i}; 
        return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function(a){ 
            switch(a){ 
                case 'yyyy':
                    return tf(t.getFullYear()); 
                    break; 
                case 'MM':
                    return tf(t.getMonth() + 1); 
                    break; 
                case 'mm':
                    return tf(t.getMinutes()); 
                    break; 
                case 'dd':
                    return tf(t.getDate()); 
                    break; 
                case 'HH':
                    return tf(t.getHours()); 
                    break; 
                case 'ss':
                    return tf(t.getSeconds()); 
                    break;
            }; 
        }); 
    };
    var sizeBottom = function() {
        var m = $(window).height() - $(".mm_navbar").height() - $(".mm_middle").height() - 340;
        if (m > 0) {
            $(".mm_bottom").css("margin-top", m + "px");
        }
    }
    if ($("#mm_prof_sex").data("sex") == 0) {
        $("#mm_prof_sex img").attr('src','http://s.mengma.com/img/women.png');
        $("#mm_prof_sex img").css({'width':'11px','height':'15px'});
    } else if ($("#mm_prof_sex").data("sex") == 1){
        $("#mm_prof_sex img").attr('src','http://s.mengma.com/img/man.png');
        $("#mm_prof_sex img").css({'width':'15px','height':'15px'});
    }


    var currentTime = new Date();
    var time1 = new Date($("#mm_prof_age").data("birth") * 1000);
    var time2 = time1.getFullYear();
    var age = currentTime.getFullYear() - time2;
    if (age > 0) {
        $("#mm_prof_age").html('16');
    } else {
        $("#mm_prof_age").html("0");
    }
    $("#mm_tablist").on("shown.bs.tab", function() {
        if (!more[$("#mm_tablist>li.active>a").data("id")]) {
            $("#mm_btn_more").html("已经到最后了");
            $("#mm_btn_more").attr("disabled", "disabled");
        } else {
            $("#mm_btn_more").html("点击加载更多");
            $("#mm_btn_more").removeAttr("disabled");
        }
    });
    var page = 0;
    var isMoreButton = false;
    var timeOrder = true;
    /**  LOAD LESSON  **/
    var loadLessonDOM = function(imgSrc, learnDegree, lessonTitle, chapter, lastLearn, nextLearn,ctype) {
        var btn = "";
        if (learnDegree == 10) {
            btn += "<div class=\"mm_prof_done text-center\"><img src=\"http://s.mengma.com/img/mm_done.png\" style=\"width:30px;height:30px;\"> 已完成</div>";
        } else {
            btn += "<a href=\"http://www.mengma.com/class/lesson/" + nextLearn + '/' +ctype + "\" class=\"text-center mm_to_learn pull-right\">继续学习</a>";
        }
        $(".mm_prof_item").eq(0).append("<div class=\"row mm_prof_lesson\"><div class=\"col-md-3\"><div style=\"position:relative;width:82px;height:66px;background:url('http://s.mengma.com/img/mm_class/" + imgSrc + "') no-repeat center center, url('http://s.mengma.com/img/mm_lesson_sprite/sprite_" + learnDegree + ".gif')  no-repeat center center;background-size:60%, 75%;margin:0 auto;\"></div>\
            </div><div class=\"col-md-6\"><h3 class=\"mm_prof_l_title\">" + lessonTitle + "</h3><p class=\"mm_prof_l_txt\">学习到 “" + chapter + "”</p><span class=\"mm_prof_l_txt\">最后学习时间</span><span class=\"mm_prof_l_txt\"> " + lastLearn + "</span>\
            </div><div class=\"col-md-3 mm_margin_t_18\">" + btn + "</div></div>");
    }
    var loadLesson = function() {
            if (!isMoreButton) {
                $(".mm_prof_item").eq(0).html("");
            }
            $.ajax({
                url: "/api/profile/getMyLessonList",
                type: "POST",
                data: {
                    uid: uid,
                },
                success: function(data) {
                    if (data) {
                        if (data.volume_list) {
                            for (var i = 0; i < data.volume_list.length; i++) {
                                learnDegree = Math.round((parseInt(data.volume_list[i].learnedSum) / parseInt(data.volume_list[i].sum)) * 10);
                                loadLessonDOM(data.volume_list[i].img, learnDegree, data.volume_list[i].title, data.volume_list[i].chapter, data.volume_list[i].recentTime, data.volume_list[i].nextLesson,data.volume_list[i].ctype);
                            }
                        } else {
                            $(".mm_prof_item").eq(0).append("<div class=\"row text-center mm_prof_none\"><h1>:(</h1><p>你太懒了，什么都没学过</p></div>");
                        }
                    }
                }
            });
        }
        /**  LOAD OJ  **/
    var loadPageTable = function(data) {
        $("#mm_oj_table").find("tbody").html("");
        for (var i = 0; i < data.length; i++) {
            $("#mm_oj_table").find("tbody").append("<tr><td class=\"mm_prof_oj_td1\">" + data[i].id + "</td><td class=\"mm_prof_oj_td2\"><a href=\"http://oj.mengma.com/quiz/" + data[i].order + "\" target=\"_blank\">" + data[i].title + "</a></td><td class=\"mm_prof_oj_td3\">" + data[i].time + "</td></tr>");
        }
    }
    var numberPerPage = 10;
    var loadOj = function() {
            if (!isMoreButton) {
                $("#mm_oj_table").find("tbody").html("");
            }
            $.ajax({
                url: "/api/profile/getMyOjList",
                type: "POST",
                data: {
                    uid: uid
                },
                success: function(data) {
                    if (data) {
                        $("#mm_prof_oj").show();
                        $("#mm_prof_oj").next().show();
                        if (data.oj_list) {
                            if (data.oj_list.length > 10) {
                                $(".pagination-holder_oj").pagination({
                                    items: data.oj_list.length,
                                    itemsOnPage: numberPerPage,
                                    prevText: "上一页",
                                    nextText: "下一页",
                                    onPageClick: function(pageNumber, event) {
                                        loadPageTable(data.oj_list.slice((pageNumber - 1) * numberPerPage, pageNumber * numberPerPage));
                                        $(window).scrollTop(0);
                                    },
                                    cssStyle: 'light-theme',
                                    displayedPages: 3,
                                    edges: 2
                                });
                            }
                            if (data.oj_list.length > 0) {
                                loadPageTable(data.oj_list.slice((1 - 1) * numberPerPage, 1 * numberPerPage));
                            }
                        } else {
                            $(".mm_prof_item").eq(1).html("");
                            $(".mm_prof_item").eq(1).append("<div class=\"row text-center mm_prof_none\"><h1>:(</h1><p>你太懒了，还没挑战过难题</p></div>");
                        }
                    }
                }
            });
        }
        /**  LOAD QUESTION  **/
    var loadQuestion = function() {
        if (!isMoreButton) {
            $(".mm_prof_item").eq(2).html("");
        }
        $.ajax({
            url: "http://api.mengma.com/questions/uid/"+uid,
            type: "GET",
            xhrFields: {
                withCredentials: true
            },
            data: {
                page: page,
                timeOrder: timeOrder,
            },
            success: function(data) {
                if (data) {
                    if (!isMoreButton) {
                        loadQuestionFrame(data.num, timeOrder);
                    }
                    if (data.questionlist) {
                        if (data.questionlist.length > 10) {
                            $(".pagination-holder_q").pagination({
                                items: data.questionlist.length,
                                itemsOnPage: numberPerPage,
                                prevText: "上一页",
                                nextText: "下一页",
                                onPageClick: function(pageNumber, event) {
                                    loadPageQ(data.questionlist.slice((pageNumber - 1) * numberPerPage, pageNumber * numberPerPage));
                                    $(window).scrollTop(0);
                                },
                                cssStyle: 'light-theme',
                                displayedPages: 3,
                                edges: 2
                            });
                        }
                        if (data.questionlist.length > 0) {
                            loadPageQ(data.questionlist.slice((1 - 1) * numberPerPage, 1 * numberPerPage));
                            $("#mm_prof_update").click(function() {
                                isMoreButton = false;
                                timeOrder = false;
                                loadQuestion();
                            });
                            $("#mm_prof_issue").click(function() {
                                isMoreButton = false;
                                timeOrder = true;
                                loadQuestion();
                            });
                        }
                    } else {
                        $(".mm_prof_q_list").append("<div class=\"row text-center mm_prof_none\"><h1>:(</h1><p>你太懒了，还没提过问题</p></div>");
                    }
                }
            }
        });
    }
    var loadQuestionFrame = function(answerNum, timeOrder) {
        var questionStatus = "";
        if (timeOrder) {
            questionStatus += "<a id=\"mm_prof_issue\" class=\"mm_color_1\" href=\"javascript:void(0)\">发布时间</a> | <a id=\"mm_prof_update\" class=\"mm_color_2\" href=\"javascript:void(0)\">更新时间</a>";
        } else {
            questionStatus += "<a id=\"mm_prof_issue\" class=\"mm_color_2\" href=\"javascript:void(0)\">发布时间</a> | <a id=\"mm_prof_update\" class=\"mm_color_1\" href=\"javascript:void(0)\">更新时间</a>";
        }
        $(".mm_prof_item").eq(2).append("<div class=\"row mm_prof_ques_title\"><div class=\"col-md-3 mm_prof_q_title_l\">" + answerNum + "个问题</div><div class=\"col-md-3 pull-right mm_prof_q_title_r\">" + questionStatus + "</div></div><div class=\"mm_prof_q_list\"></div><div id=\"mm_prof_q_loadmore\">\
            <div class=\"row\" style=\"margin-top:10px;\"><div class=\"col-lg-12\"><div class=\"pagination-holder_q\" style=\"float:right;\"></div></div></div></div>");
    }
    var loadQContent = function(url, answerNum, title, time) {
        $(".mm_prof_q_list").append("<div class=\"row mm_prof_q_item\"><div class=\"col-md-1 mm_prof_q_comment\"><i class=\"fa fa-comment-o\"></i> " + answerNum + "</div>\
                <div class=\"col-md-9 mm_prof_q_title\"><a href=\"" + url + "\" class=\"mm_prof_q_a\" target=\"_blank\">" + title + "</a></div><div class=\"col-md-2 mm_profile_question_time\">" + time + "</div></div>");
    }
    var loadPageQ = function(data) {
            $(".mm_prof_q_list").html("");
            for (var i = 0; i < data.length; i++) {
                try{
                    var title = decodeURIComponent(data[i].title);
                }catch(e) {}
                if (title.length > 50) {
                    title = title.substr(0, 50) + "...";
                }
                var time = format(data[i].time*1000, 'yyyy-MM-dd');
                loadQContent(data[i].url, data[i].answer_num, title, time);
            }
        }
        /**  LOAD ANSWER  **/
    var loadAnswer = function() {
        if (!isMoreButton) {
            $(".mm_prof_item").eq(3).html("");
        }
        $.ajax({
            url: "http://api.mengma.com/answers/uid/"+uid,
            type: "GET",
            xhrFields: {
                withCredentials: true
            },
            data: {
                page: page,
            },
            success: function(data) {
                if (data) {
                    if (!isMoreButton) {
                        loadAnswerFrame(data.num);
                    }
                    if (data.answerlist) {
                        if (data.answerlist.length > 10) {
                            $(".pagination-holder_a").pagination({
                                items: data.answerlist.length,
                                itemsOnPage: numberPerPage,
                                prevText: "上一页",
                                nextText: "下一页",
                                onPageClick: function(pageNumber, event) {
                                    loadPageA(data.answerlist.slice((pageNumber - 1) * numberPerPage, pageNumber * numberPerPage));
                                    $(window).scrollTop(0);
                                },
                                cssStyle: 'light-theme',
                                displayedPages: 3,
                                edges: 2
                            });
                        }
                        if (data.answerlist.length > 0) {
                            loadPageA(data.answerlist.slice((1 - 1) * numberPerPage, 1 * numberPerPage));
                        }
                    } else {
                        $(".mm_prof_a_list").append("<div class=\"row text-center mm_prof_none\"><h1>:(</h1><p>你太懒了，还没回答过问题</p></div>");
                    }
                }
            }
        });
    }
    
    var achievement = function(){
        $.ajax({
            url: "http://api.mengma.com/user/record/"+uid,
            type: "GET",
            xhrFields: {
                withCredentials: true
            },
            success:function(data){
                $(".mm_prof_padding_lesson").html('');
                $(".mm_prof_padding_lesson").append('<div class=\"mm_prof_study\"><h1>:(</h1><p>竟然什么都没有</p><p class=\"mm_prof_study_p\"><a href=\"http:\/\/www.mengma.com\/volumes\">快去学习</a>发现课程里的宝藏</p></div>');
                if(data.studying.length > 0){
                    $(".mm_prof_padding_lesson").html('');
                    var username = "萌萌的你";
                    if(!data.myown) {
                        username = data.username;
                    }
                    $(".mm_prof_padding_lesson").append("<div class=\"mm_prof_achievement\"><img src=\"http:\/\/s.mengma.com\/img\/riband.png\"><p>"+username+"，共获得了<span></span>枚勋章</p></div>");;
                    $(".mm_prof_achievement span").text(data.medal_num);
                    for(var i in data.studying){
                        var shareBtn = "";
                        if(data.myown) {
                            shareBtn = "<div onmouseover=\"setShare('"+data.studying[i].title+"','"+data.studying[i].getmedal+"','"+data.studying[i].img+"','"+data.studying[i].vid+"')\" class=\"jiathis_style_32x32\"><a class=\"jiathis_button_qzone\"></a><a class=\"jiathis_button_tsina\"></a><a class=\"jiathis_button_weixin\"></a></div>";
                        }
                        $(".mm_prof_padding_lesson").append("<div class=\"mm_prof_achievement_section col-md-12\"><div> <div class=\"share_data\" style=\"dispaly:none\"> <h1>1</h1> <h2>8</h2><h3>html</h3></div> </div><div class=\"mm_prof_achievement_section_b\"><div class=\"mm_prof_achievement_section_b_l\"><div><img src=\"http:\/\/s.mengma.com\/\/img\/mm_class\/html2.png\"><p>编程基础</p><span>分享到</span></div>" + shareBtn + "</div><div class=\"mm_prof_achievement_section_b_r\"><div></div></div></div></div>");
                        $(".mm_prof_achievement_section_b_l").eq(i).find('p').text(data.studying[i].title);
                        $(".mm_prof_achievement_section_b_l").eq(i).find('img').attr('src',data.studying[i].img);
                        for(var m=0;m<data.studying[i].medal.length;m++){
                            $(".mm_prof_achievement_section_b_r").eq(i).find('div').append("<img data-toggle=\"tooltip\" data-placement=\"top\" data-html=\"true\" title=\"\" data-original-title=\"\">");
                            $(".mm_prof_achievement_section_b_r").eq(i).find('img').eq(m).attr('src',data.studying[i].medal[m].img);
                            $(".mm_prof_achievement_section_b_r").eq(i).find('img').eq(m).attr('data-original-title',data.studying[i].medal[m].name);
                            $('[data-toggle="tooltip"]').tooltip();
                            if(data.studying[i].medal[m].usermedal == false){
                                $(".mm_prof_achievement_section_b_r").eq(i).find('img').eq(m).css({'opacity':0.3});
                            }
                            if(data.studying[i].medal.length > 6){          
                                $($('.mm_prof_achievement_section_b_r')[i]).find('img').eq(m).css({'margin-top':"13px"});
                            }
                        }

                    }
                }

            }   
        })
        setTimeout(function(){
            $("body").append("<script>function setShare(title, how ,url, vid) {console.dir(title);console.dir(vid);console.dir(title);jiathis_config.title = \"我正在@萌码 学习#\"+title+\"#课程，感觉编程变的越来越有趣了~\";jiathis_config.pic = url;jiathis_config.url = \"http:\/\/s.mengma.com\/frontEnd\/#\/share\/lesson\/clean-up\/\"+vid+\"?uid="+uid+"\";} var jiathis_config = {title:\"我正在@萌码 学习 #HTML CSS基础#课程，感觉编程变的越来越有趣了，而且已经攒到了\"+$(\".mm_prof_achievement span\").text()+\"枚勋章咯~\",summary:\"而且已经攒到了\"+$(\".mm_prof_achievement span\").html()+\"枚勋章咯~现在感觉棒棒哒~快来跟我一起coding吧，看谁攒的多\",pic: \"http:\/\/s.mengma.com\/img\/mm_class\/html.png\",data_track_clickback:true,ralateuid:{\"tsina\": \"5296436353\"},appkey:{\"tsina\": \"4092659152\"},shortUrl: false,hideMore: false}</script>");
            $("body").append("<script type=\"text/javascript\" src=\"http:\/\/v3.jiathis.com\/code\/jia.js\?uid=1962012\" charset=\"utf-8\"></script>")
        },500)

    }

    var loadAnswerFrame = function(answerNum) {
        $(".mm_prof_item").eq(3).append("<h2 class=\"mm_prof_a_title\">" + answerNum + "个回答</h2><div class=\"mm_prof_a_list\"></div><div id=\"mm_prof_a_loadmore\"><div class=\"row\" style=\"margin-top:10px;\"><div class=\"col-lg-12\"><div class=\"pagination-holder_a\" style=\"float:right;\"></div></div></div></div>");
    }
    var loadAContent = function(url, likeNum, title, userBack, answerContent, time) {
        $(".mm_prof_a_list").append("<a href=\"" + url + "\" target=\"_blank\"><div class=\"row mm_prof_a_item\"><div class=\"col-md-1 mm_prof_a_like\"><i class=\"fa fa-thumbs-up\"></i> " + likeNum + "</div>\
                <div class=\"col-md-9\"><div class=\"row mm_prof_q_title\"><a href=\"" + url + "\" class=\"mm_\" target=\"_blank\">" + title + "</a></div><div class=\"row mm_prof_a_reply\">回复 \"" + userBack + "\" &nbsp;&nbsp;" + answerContent + "</div>\
                </div><div class=\"col-md-2 mm_prof_q_time\">" + time + "</div></div></a>");
    }
    function delHtmlTag(str){
        return str.replace(/<[^>]+>/g,"");//去掉所有的html标记
    }
    var loadPageA = function(data) {
        $(".mm_prof_a_list").html("");
        try{
            for (var i = 0; i < data.length; i++) {
                var title = decodeURIComponent(data[i].title);
                if (title.length > 50) {
                    title = title.substr(0, 50) + "...";
                }
                var answerContent = decodeURIComponent(data[i].content);
                answerContent = delHtmlTag(answerContent);
                if (answerContent.length > 40) {
                    answerContent = answerContent.substr(0, 40) + "...";
                }
                var time = format(data[i].time*1000, 'yyyy-MM-dd');
                var nickname = data[i].user.name;
                if(data[i].nickname == "") {
                    nickname = "萌小码"+data[i].user.uid;
                }
                loadAContent(data[i].url, data[i].like_num, title, nickname, answerContent, time);
            }
        } catch(e){}
    }

    
    circleWidth = parseInt(Math.pow($(".mm_prof_item").width(), 1 / 2) * 3);
    var intervals = [parseInt($(".first-circle").data("target")) / 100, parseInt($(".second-circle").data("target")) / 100];
    counter = 1;
    $(".first-circle").knob({
        'min': 0,
        'max': 100,
        'width': 76,
        'height': 150,
        'readOnly': true,
        'thickness': 0.15,
        'fgColor': '#82bf71',
        'bgColor': '#eee',
        'inputColor': '#82bf71',
        'format': function(val) {
            return val + "%";
        }
    });
    $(".second-circle").knob({
        'min': 0,
        'max': 100,
        'width': 76,
        'height': 150,
        'readOnly': true,
        'thickness': 0.15,
        'fgColor': '#f4a34d',
        'bgColor': '#eee',
        'inputColor': '#f4a34d',
        'format': function(val) {
            return val + "%";
        }
    });
    gogogo = function() {
        $.map($(".first-circle, .second-circle"), function(elem, i) {
            $(elem).val(intervals[i] * counter).trigger("change");
        });
        counter++;
        if (counter <= 100) {
            interval = counter > 90 ? counter : Math.pow(counter, 1 / 2);
            setTimeout("gogogo()", interval);
        } else {
            counter = 1;
        }
    }
    $(".mm_prof_title").click(function() {
        sizeBottom();
        var ojTable = "";
        var learnDegree;
        $(".mm_prof_title").eq($(this).data("id")).addClass("mm_prof_title_active").siblings().removeClass("mm_prof_title_active")
        $(".mm_prof_item").eq($(this).data("id")).addClass("active").siblings().removeClass("active");
        if ($(this).data("id") == 0) {
            page = 0;
            isMoreButton = false;
            achievement();
        } else if ($(this).data("id") == 1) {
            page = 0;
            isMoreButton = false;
            loadOj();
            gogogo();
        } else if ($(this).data("id") == 2) {
            page = 0;
            isMoreButton = false;
            loadQuestion();
        } else if ($(this).data("id") == 3) {
            page = 0;
            isMoreButton = false;
            loadAnswer();
        }
    });
    $(".mm_prof_title").eq(0).click();
    $('[data-toggle="tooltip"]').tooltip();

});